package com.gcsoftware.Interceptor;

import com.gcsoftware.beans.SysLog;
import com.gcsoftware.web.mapper.db.LoginMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import static com.gcsoftware.Interceptor.LoginCache.USER_NAME;
import static com.gcsoftware.configs.AppConstants.Log.LOG_PREFIX;
import static com.gcsoftware.configs.AppConstants.Log.LOG_SUFFIX;
import static com.gcsoftware.configs.AppConstants.Sys.*;

/**
 * Session 监听器
 * @author czp
 * date 2018-05-29
 */
@WebListener
@Service
public class SessionListener implements HttpSessionListener {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private LoginMapper loginMapper;

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        logger.info(LOG_PREFIX.getValue() + " session create ... " + LOG_SUFFIX.getValue());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        logger.info(LOG_PREFIX.getValue() + " session destroy ... " + LOG_SUFFIX.getValue());
        String sessionId = httpSessionEvent.getSession().getId();
        String cacheSessionId = LoginCache.LOGIN_SESSION_ID.get(SYS_SESSION_ID.getValue());
        if (sessionId.equals(cacheSessionId)) {
            String cacheIp = LoginCache.LOGIN_IP.get(SYS_LOGIN_IP.getValue());
            String cacheBrowser = LoginCache.LOGIN_BROWSER.get(SYS_LOGIN_BROWSER.getValue());
            LoginCache.LOGIN_SESSION_ID.remove(SYS_SESSION_ID.getValue());
            LoginCache.LOGIN_IP.remove(SYS_LOGIN_IP.getValue());
            LoginCache.LOGIN_BROWSER.remove(SYS_LOGIN_BROWSER.getValue());
            loginMapper.recordLog(new SysLog( USER_NAME, cacheIp, cacheBrowser, SYS_SESSION_TIME_OUT.getName() ));
        }
    }
}
